package viz.model.flare.proxies
{
	import flare.vis.data.Data;
	import flare.vis.data.EdgeSprite;
	import flare.vis.data.NodeSprite;
	
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;
	
	import viz.model.flare.data.ActionItem;
	import viz.model.flare.data.StateItem;

	public class FlareDataProxy extends Proxy
	{
		public static const NAME:String = "FlareDataProxy";
		
		public static const FLARE_DATA_UPDATED:String = "flareData/updated";
		
		private var decoder:Class;
		
		public function FlareDataProxy(decoder:Class):void
		{
			initProxy(decoder)
			super(NAME);
		
		}
		
		private function initProxy(decoder:Class):void{
			this.decoder = decoder;
		}
		
		override public function setData( data:Object ):void{
			super.data = new decoder( data ).decode( );
			sendDataUpdated();
		}		
		
		public function getEdge( o:Object ):EdgeSprite{
			switch(true){
				case(o is EdgeSprite): return EdgeSprite(o);
				case(o is ActionItem): return getActionAsEdge(ActionItem(o));
				case(o is String): return getEdgeFromName(String(o));
				default: return null;
			}
		}
		
		private function getEdgeFromName( name:String ):EdgeSprite{
			var a:Array = flareData.edges.toDataArray(),
				n:int,
				item:ActionItem;
			for each ( item in a ){
				if( item.name == name )break;
			}
			return flareData.edges[n];
		}
		
		private function getActionAsEdge( action:ActionItem ):EdgeSprite{
			var a:Array = flareData.edges.toDataArray(),
				index:int = a.indexOf( action  );
			return flareData.edges[index];
		}
		
		public function getNode( o:Object ):NodeSprite{
			switch(true){
				case(o is NodeSprite): return NodeSprite(o);
				case(o is StateItem): return getStateAsNode(StateItem(o));
				case(o is String): return getNodeFromName(String(o));
				default: return null;
			}
		}
		
		private function getNodeFromName( name:String ):NodeSprite{
			var a:Array = flareData.nodes.toDataArray(),
				n:int,
				item:StateItem;
			for each ( item in a ){
				if( item.fullPath == name || item.name == name )break;
			}
			return flareData.nodes[n];
		}
		
		private function getStateAsNode( state:StateItem ):NodeSprite{
			var a:Array = flareData.nodes.toDataArray(),
				index:int = a.indexOf( state  );
			return flareData.nodes[index];
		}
		
		
		private function get flareData():Data{
			return Data( data );
		}
		
		private function sendDataUpdated():void{
			sendNotification(FLARE_DATA_UPDATED, getData());
		}
		
	}
}